package com.gopay.bis.pab.expay.operation;

import java.security.PrivateKey;
import java.security.PublicKey;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.pab.expay.rsa.CryptoUtil;
import com.gopay.bis.pab.expay.rsa.XmlSignatureHelper;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.ipay.ebank.IpayMessage;
import com.gopay.common.domain.bank.pab.expay.PabExPayMessage;
import com.gopay.common.domain.bank.pab.expay.req.req.FastpayCPReq;
import com.gopay.common.domain.bank.pab.expay.req.req.FastpayFPAReq;
import com.gopay.common.domain.bank.pab.expay.req.req.FastpaySOQReq;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;

/**
 * 
 * @ClassName: PabExPayCertHelper 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author ShenJun 
 * @date 2016年11月29日 下午4:23:56
 */
public class PabExPayCertHelper implements ICertHelper {

    private static Log logger = LogFactory.getLog(PabExPayCertHelper.class);
    
    
	@Override
	public String sign(BaseMessage baseMessage) throws GopayException {
	    
	    String signData = "";
	    PabExPayMessage message = (PabExPayMessage) baseMessage;
        try {
            String cerFilePath = baseMessage.getPublicKeyPath();
            String pfxFilePath = baseMessage.getPrivateKeyPath();
            String priKeyPsw  = baseMessage.getPrivatePwd();
            //获取RSA私钥对象
            PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix(pfxFilePath, "pfx", priKeyPsw, "RSA");
            //数字签名（签名部分为Message节点里面的部分），并用base64加密
            XmlSignatureHelper xmlSignatureHelper = new XmlSignatureHelper(pfxFilePath, priKeyPsw);
            //System.out.println("~~~~~~~~message.getPlainMessage:" + message.getPlainMessage());
            signData = xmlSignatureHelper.sign(message.getPlainMessage(),getBussType(message), hzfPriKey);
            message.setSignMessage(signData);
        } catch (Exception e) {
            BankLogUtils.printExPaySignExceptionLog(baseMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6029);
        }
        return signData;
        
	}

	@Override
	public Object verify(BaseMessage baseMessage) throws GopayException {
	    boolean verifySign = false;
        try {
        	String cerFilePath = baseMessage.getPublicKeyPath();
            String pfxFilePath = baseMessage.getPrivateKeyPath();
            String priKeyPsw  = baseMessage.getPrivatePwd();
        	PabExPayMessage message = (PabExPayMessage) baseMessage;
            //获取RSA公钥对象
            PublicKey hzfPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix(cerFilePath, "crt", "RSA");
            //用base64解密
            XmlSignatureHelper xmlSignatureHelper = new XmlSignatureHelper(pfxFilePath, priKeyPsw);
            verifySign = xmlSignatureHelper.verify(message.getSignMessage(), hzfPubKey);
            logger.error("平安快捷验签结果：" + verifySign);
        } catch (Exception e) {
            BankLogUtils.printExPayVerifyExceptionLog(baseMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
        }

        return verifySign;
	    
	    
	    
	}
	
	/**
	 * 
	 * @Description: 截取xml字符串里面的子xml字符串，如xml为"<a><b></b></a>",nodeName为"a",则返回结果为<b></b>
	 * @param xml  源xml格式的字符串
	 * @param nodeName  需要截取的xml节点名称
	 * @return 
	 * @author ShenJun
	 */
	private static String getInnerXml(String xml,String nodeName){
	    String startNode = "<" + nodeName;
        String endNode = "</" + nodeName + ">";
        return xml.substring(xml.indexOf(">", xml.indexOf(startNode)) + 1,xml.indexOf(endNode));
    }
	
	public static void main(String[] args) {
		String str = " <Fastpay><Message id=\"1481704642935\"><FPAReq id=\"FPAReq\"><instId>1248</instId><name>平安测试一七八四一</name><date>20161214163722</date><certType>1</certType><certNo>123421198208233613</certNo><cardType>D</cardType><cardNo>6230583000003338755</cardNo><mobilePhone>13725581123</mobilePhone><Extension></Extension></FPAReq></Message></Fastpay>";
		//String pfxFilePath = "D:\\jobjob\\doc\\快捷支付_开发文档\\平安银行\\key\\test\\fastpay.pfx";
		//String cerFilePath = "D:\\jobjob\\doc\\快捷支付_开发文档\\平安银行\\key\\test\\fastpay.cer";
		String pfxFilePath = "D:\\jobjob\\doc\\快捷支付_开发文档\\平安银行\\key\\pro\\fastpay.pfx";
		String cerFilePath = "D:\\jobjob\\doc\\快捷支付_开发文档\\平安银行\\key\\pro\\fastpay.cer";
		String priKeyPsw = "12345678";
		String signNode = "FPAReq";
		 try {
			 PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix(pfxFilePath, "pfx", priKeyPsw, "RSA");
	            //数字签名（签名部分为Message节点里面的部分），并用base64加密
	            XmlSignatureHelper xmlSignatureHelper = new XmlSignatureHelper(pfxFilePath, priKeyPsw);
	           String signData = xmlSignatureHelper.sign(str,signNode, hzfPriKey);
	         System.out.println(signData);
	         
	         PublicKey hzfPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix(cerFilePath, "crt", "RSA");
	         System.out.println("~~~~~~~~~"+hzfPubKey);
	         String ss= "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><Fastpay><Message id=\"1481794449488\"><FPARes id=\"FPARes\"><signNo>6230583000003338755</signNo><remark/><date>20161215</date><instId>1248</instId><Extension/><AcntType>1</AcntType><TokenNo>FA201612150001966736</TokenNo></FPARes><Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><SignedInfo><CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"/><SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/><Reference URI=\"#FPARes\"><Transforms><Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/></Transforms><DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/><DigestValue>6eFbAyLf2HybE6G0/jmYYqBLnlk=</DigestValue></Reference></SignedInfo><SignatureValue>gK7YbSi86cVdEeGo5lgsUj/RivL/CpE4rNfxzcZ95aoRIV5Cv50pX3q2J31KsBmV12Io6FbGDSc8"
+"YCcv22qxi6+yZnhjtnjftCJZWUDP69QRHsj9haVA4N1UCtkRLfSZXPEVS95G47Es+C/tyHyTTFj4"
+"DFPROiQ2QbYAW7mXwjQ=</SignatureValue></Signature></Message></Fastpay>";
	           boolean  verifySign = xmlSignatureHelper.verify(signData, hzfPubKey);
	           System.out.println(verifySign);
	     } catch (Exception e) {
	         e.printStackTrace();
	     }
	}
	
	/**
	 * 获取业务
	 * @param msg
	 * @return
	 */
	private static String getBussType(PabExPayMessage msg){
		if(msg.getPlainMessage().indexOf("</FPAReq>") > 0){
			return "FPAReq";
		} else if(msg.getPlainMessage().indexOf("</CPReq>") > 0){
			return "CPReq";
		} else if(msg.getPlainMessage().indexOf("</SOQReq>") > 0){
			return "SOQReq";
		} else if(msg.getPlainMessage().indexOf("</SOQReqH>") > 0){
			return "SOQReqH";
		} else if(msg.getPlainMessage().indexOf("</FSPReq>") > 0){
			return "FSPReq";
		} else{
			return null;
		}
	}
}
